import hashlib
import hmac
import os
from datetime import datetime, timedelta
import jwt
from flask import current_app


def generate_password_hash(password):
    """使用PBKDF2生成安全的密码哈希"""
    salt = os.urandom(16)
    key = hashlib.pbkdf2_hmac(
        'sha256',
        password.encode('utf-8'),
        salt,
        100000
    )
    return f"{salt.hex()}:{key.hex()}"


def check_password_hash(stored_hash, password):
    """验证密码哈希"""
    try:
        salt_hex, key_hex = stored_hash.split(':')
        salt = bytes.fromhex(salt_hex)
        stored_key = bytes.fromhex(key_hex)

        new_key = hashlib.pbkdf2_hmac(
            'sha256',
            password.encode('utf-8'),
            salt,
            100000
        )
        return hmac.compare_digest(stored_key, new_key)
    except ValueError:
        return False


def generate_reset_token(user):
    """生成密码重置令牌"""
    payload = {
        'reset': user.id,
        'exp': datetime.utcnow() + timedelta(seconds=current_app.config['PASSWORD_RESET_EXPIRY'])
    }
    return jwt.encode(payload, current_app.config['SECRET_KEY'], algorithm='HS256')


def verify_reset_token(token):
    """验证密码重置令牌"""
    try:
        payload = jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=['HS256'])
        user_id = payload.get('reset')
        if user_id:
            from app.models.user import User
            return User.query.get(user_id)
    except jwt.ExpiredSignatureError:
        return None
    except jwt.InvalidTokenError:
        return None
    return None

